package com.freewater.parking.infrastructure.query;

import com.freewater.parking.infrastructure.db.SummaryDao;
import com.freewater.parking.infrastructure.db.SummaryTable;
import com.freewater.parking.domain.common.DomainEventListener;
import com.freewater.parking.domain.common.DomainEvent;
import com.freewater.parking.domain.parking.CheckedInEvent;
import com.freewater.parking.domain.parking.CheckedOutEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class SummaryMaterializer implements DomainEventListener {

    private final SummaryDao summaryDao;

    public SummaryMaterializer(SummaryDao summaryDao) {
        this.summaryDao = summaryDao;
    }

    @Override
    public void onEvent(DomainEvent event) {
        if (event instanceof CheckedInEvent) {
            this.updateParkingCount(1);
        } else if (event instanceof CheckedOutEvent) {
            this.updateParkingCount(-1);
        }
    }

    private void updateParkingCount(int increment) {
        this.summaryDao.updateParkingCountById(SummaryTable.SINGLE_ID, increment);
    }
}
